package com.person.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.person.mapper.ComplaintInfoMapper;
import com.person.mapper.DepartmentMapper;
import com.person.model.dto.DepartmentDto;
import com.person.model.entity.*;
import com.person.model.vo.ComplaintBaseInfoVo;
import com.person.model.vo.ComplaintInfoVo;
import com.person.service.*;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class ComplaintInfoServiceImpl extends ServiceImpl<ComplaintInfoMapper, ComplaintInfo> implements ComplaintInfoService {

    @Resource
    private ComplaintInfoMapper complaintInfoMapper;

    @Resource
    private ComplainantInfoService complainantInfoService;

    @Resource
    private AgentInfoService agentInfoService;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private ContactsService contactsService;

    @Resource
    private ComplaintAcceptanceService complaintAcceptanceService;

    @Resource
    private RegisterAcceptanceService registerAcceptanceService;

    @Override
    public Page<ComplaintInfo> pageItem(Page<ComplaintInfo> page, ComplaintInfoVo complaintInfoVo) {

        complaintInfoVo = Optional.ofNullable(complaintInfoVo).orElse(new ComplaintInfoVo());

        LambdaQueryWrapper<ComplaintInfo> complaintInfoWrapper = new LambdaQueryWrapper<>();
        complaintInfoWrapper.eq(StringUtils.hasText(complaintInfoVo.getRegistrationNo()), ComplaintInfo::getRegistrationNo, complaintInfoVo.getRegistrationNo());
        complaintInfoWrapper.eq(StringUtils.hasText(complaintInfoVo.getComplainant()), ComplaintInfo::getComplainant, complaintInfoVo.getComplainant());
        complaintInfoWrapper.eq(StringUtils.hasText(complaintInfoVo.getAgent()), ComplaintInfo::getAgent, complaintInfoVo.getAgent());
        complaintInfoWrapper.eq(StringUtils.hasText(complaintInfoVo.getSource()), ComplaintInfo::getSource, complaintInfoVo.getSource());
        complaintInfoWrapper.eq(complaintInfoVo.getIsAcceptance() != null, ComplaintInfo::getIsAcceptance, complaintInfoVo.getIsAcceptance());
        complaintInfoWrapper.eq(complaintInfoVo.getIsRegister() != null, ComplaintInfo::getIsRegister, complaintInfoVo.getIsRegister());
        complaintInfoWrapper.like(StringUtils.hasText(complaintInfoVo.getComplaintDesc()), ComplaintInfo::getComplaintDesc, complaintInfoVo.getComplaintDesc());
        if (complaintInfoVo.getComplaintDateList() != null) {
            complaintInfoWrapper.between(ComplaintInfo::getComplaintDate, complaintInfoVo.getComplaintDateList().get(0), complaintInfoVo.getComplaintDateList().get(1));
        }
        if (complaintInfoVo.getUpdateTimeList() != null) {
            complaintInfoWrapper.between(ComplaintInfo::getUpdateTime, complaintInfoVo.getUpdateTimeList().get(0), complaintInfoVo.getUpdateTimeList().get(1));
        }
        return complaintInfoMapper.selectPage(page, complaintInfoWrapper);

    }

    @Override
    @Transactional
    public void addOrUpdateComplaintInfo(ComplaintBaseInfoVo complaintBaseInfoVo) {
        //根据身份证号保存或更新投诉人信息,此功能不是根据id去修改投诉人的个人信息
        ComplainantInfo complainantInfo = complaintBaseInfoVo.getComplainantInfo();

        LambdaQueryWrapper<ComplainantInfo> complainantInfoWrapper = new LambdaQueryWrapper<>();
        complainantInfoWrapper.eq(ComplainantInfo::getIdNo, complainantInfo.getIdNo());
        ComplainantInfo complainantInfoDb = complainantInfoService.getOne(complainantInfoWrapper);
        if (complainantInfoDb == null) {
            complainantInfoService.save(complainantInfo);
        } else {
            complainantInfo.setId(complainantInfoDb.getId());
            complainantInfoService.update(complainantInfo, complainantInfoWrapper);
        }


        //根据社会统一编码保存或更新被投诉人信息
        AgentInfo agentInfo = complaintBaseInfoVo.getAgentInfo();

        LambdaQueryWrapper<AgentInfo> agentInfoWrapper = new LambdaQueryWrapper<>();
        agentInfoWrapper.eq(AgentInfo::getCreditCode, agentInfo.getCreditCode());
        if (agentInfoService.getOne(agentInfoWrapper) == null) {
            agentInfoService.save(agentInfo);
        } else {
            agentInfoService.update(agentInfo, agentInfoWrapper);
        }

        RegisterAcceptance registerAcceptance = complaintBaseInfoVo.getRegisterAcceptance();
        ComplaintInfo complaintInfo = new ComplaintInfo();

        //如果是其他部门移送的需要保存这个部门的id
        DepartmentDto departmentDto = complaintBaseInfoVo.getTransferDepartmentDto();
        Integer departmentNewId = 0;

        if (departmentDto != null && departmentDto.getName() != null) {
            LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Department::getName, departmentDto.getName());
            //根据部门名称去查询有没有这个部门
            Department departmentDb = departmentMapper.selectOne(queryWrapper);

            List<Contacts> contactsList = departmentDto.getContactsList();
            //没有就保存这个部门信息和此部门的联系人
            if (departmentDb == null) {
                departmentDto.setId(null);
                departmentMapper.insert(departmentDto);
                departmentNewId = departmentDto.getId();
                for (Contacts contacts : contactsList) {
                    contacts.setId(null);
                    contacts.setDepartmentId(departmentNewId);
                }
                contactsService.saveBatch(contactsList);
            } else { //有就拿部门id,把之前联系人删除，并重新保存
                departmentNewId = departmentDb.getId();
                departmentMapper.updateById(departmentDto);
                LambdaQueryWrapper<Contacts> contactsQueryWrapper = new LambdaQueryWrapper<>();
                contactsQueryWrapper.eq(Contacts::getDepartmentId, departmentNewId);
                contactsService.remove(contactsQueryWrapper);
                for (Contacts contacts : contactsList) {
                    contacts.setDepartmentId(departmentNewId);
                }
                contactsService.saveBatch(contactsList);
            }
            complaintInfo.setTransferDepartmentId(departmentNewId);
        }
        // 保存投诉信息
        Integer baseInfoVoId = complaintBaseInfoVo.getId();
        String complaintDesc; //对争议事实预处理
        if (complaintBaseInfoVo.getComplaintDesc().endsWith("。")) {
            complaintDesc = complaintBaseInfoVo.getComplaintDesc();
        } else {
            complaintDesc = complaintBaseInfoVo.getComplaintDesc() + "。";
        }
        if (baseInfoVoId != null) {
            LambdaUpdateWrapper<ComplaintInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(ComplaintInfo::getId, baseInfoVoId);
            lambdaUpdateWrapper.set(ComplaintInfo::getSource, complaintBaseInfoVo.getSource());
            lambdaUpdateWrapper.set(ComplaintInfo::getComplaintDesc, complaintDesc);

            if (departmentDto != null && departmentDto.getName() != null) {
                lambdaUpdateWrapper.set(ComplaintInfo::getTransferDepartmentId, departmentNewId);
            } else {
                lambdaUpdateWrapper.set(ComplaintInfo::getTransferDepartmentId, null);
            }
            lambdaUpdateWrapper.set(ComplaintInfo::getCreditCode, complaintBaseInfoVo.getAgentInfo().getCreditCode());
            lambdaUpdateWrapper.set(ComplaintInfo::getComplainantId, complainantInfo.getId());
            lambdaUpdateWrapper.set(ComplaintInfo::getComplainant, complainantInfo.getName());
            lambdaUpdateWrapper.set(ComplaintInfo::getAgent, agentInfo.getName());
            lambdaUpdateWrapper.set(ComplaintInfo::getCreditCode, agentInfo.getCreditCode());

            complaintInfoMapper.update(lambdaUpdateWrapper);

            //更新受理投诉表的内容
            LambdaUpdateWrapper<ComplaintAcceptance> complaintAcceptanceWrapper = new LambdaUpdateWrapper<>();
            complaintAcceptanceWrapper.eq(ComplaintAcceptance::getComplaintInfoId, baseInfoVoId)
                    .set(ComplaintAcceptance::getIsAcceptance, complaintBaseInfoVo.getIsAcceptance())
                    .set(ComplaintAcceptance::getAcceptanceDate, complaintBaseInfoVo.getAcceptanceDate())
                    .set(ComplaintAcceptance::getMediateDate, complaintBaseInfoVo.getMediateDate())
                    .set(ComplaintAcceptance::getSituation, complaintBaseInfoVo.getAcceptanceSituation())
                    .set(ComplaintAcceptance::getContactsId, complaintBaseInfoVo.getContactsId());
            complaintAcceptanceService.update(complaintAcceptanceWrapper);

            //跟新立案表的内容
            LambdaUpdateWrapper<RegisterAcceptance> registerAcceptanceWrapper = new LambdaUpdateWrapper<>();
            registerAcceptanceWrapper.eq(RegisterAcceptance::getComplaintInfoId, baseInfoVoId)
                    .set(RegisterAcceptance::getIsRegister, registerAcceptance.getIsRegister())
                    .set(RegisterAcceptance::getRegisterDate, registerAcceptance.getRegisterDate())
                    .set(RegisterAcceptance::getCause, registerAcceptance.getCause())
                    .set(RegisterAcceptance::getSituation, registerAcceptance.getSituation());
            registerAcceptanceService.update(registerAcceptanceWrapper);
        } else {
            Integer departmentId = complaintBaseInfoVo.getDepartmentId();
            Department department = departmentMapper.selectById(departmentId);
            Integer code = department.getCode();
            LambdaQueryWrapper<ComplaintInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByDesc(ComplaintInfo::getId);
            wrapper.last("LIMIT 1");
            int id = 1;
            ComplaintInfo complaintInfo1 = this.getOne(wrapper);
            if (complaintInfo1 != null) {
                String[] split = complaintInfo1.getNumber().split("-");
                id = Integer.parseInt(split[1]) + 1;
            }
            BeanUtils.copyProperties(complaintBaseInfoVo, complaintInfo);
            String number;
            if (id < 10) {
                number = code + "-00" + id;
            } else if (id < 100) {
                number = code + "-0" + id;
            } else {
                number = code + "-" + id;
            }
            complaintInfo.setNumber(number);

            //新增注册号的逻辑
            int year = complaintBaseInfoVo.getComplaintDate().getYear();
            wrapper.clear();
            wrapper.like(ComplaintInfo::getRegistrationNo, year)
                    .orderByDesc(ComplaintInfo::getId).last("LIMIT 1");

            int idRegistration = 1;
            ComplaintInfo complaintInfo2 = this.getOne(wrapper);
            if (complaintInfo2 != null) {
                String[] split = complaintInfo2.getRegistrationNo().split("-");
                idRegistration = Integer.parseInt(split[1]) + 1;
            }
            String registrationNo;
            if (idRegistration < 10) {
                registrationNo = year + "-00" + idRegistration;
            } else if (idRegistration < 100) {
                registrationNo = year + "-0" + idRegistration;
            } else {
                registrationNo = year + "-" + idRegistration;
            }
            complaintInfo.setRegistrationNo(registrationNo);
            complaintInfo.setComplainantId(complainantInfo.getId());
            complaintInfo.setComplainant(complainantInfo.getName());
            complaintInfo.setCreditCode(agentInfo.getCreditCode());
            complaintInfo.setAgent(agentInfo.getName());
            complaintInfo.setIsAcceptance(0);
            complaintInfo.setIsRegister(0);
            complaintInfo.setUpdateTime(LocalDateTime.now());
            complaintInfo.setComplaintDesc(complaintDesc);
            if (departmentNewId != 0) {
                complaintInfo.setTransferDepartmentId(departmentNewId);
            }
            complaintInfo.setFilingHandlingDate(registerAcceptance.getRegisterDate());
            this.save(complaintInfo);

            //保存受理投诉表的内容
            ComplaintAcceptance complaintAcceptance = new ComplaintAcceptance();
            complaintAcceptance.setIsAcceptance(complaintBaseInfoVo.getIsAcceptance());
            complaintAcceptance.setAcceptanceDate(complaintBaseInfoVo.getAcceptanceDate());
            complaintAcceptance.setMediateDate(complaintBaseInfoVo.getMediateDate());
            complaintAcceptance.setSituation(complaintBaseInfoVo.getAcceptanceSituation());
            complaintAcceptance.setComplaintInfoId(complaintInfo.getId());
            complaintAcceptance.setContactsId(complaintBaseInfoVo.getContactsId());
            complaintAcceptanceService.save(complaintAcceptance);
            //新增立案表的记录
            registerAcceptance.setComplaintInfoId(complaintInfo.getId());
            registerAcceptanceService.save(registerAcceptance);
        }
        LambdaUpdateWrapper<ComplaintInfo> complaintInfoWrapper = new LambdaUpdateWrapper<>();

        if (complaintInfo.getId() != null) {
            complaintInfoWrapper.eq(ComplaintInfo::getId, complaintInfo.getId());
        } else {
            complaintInfoWrapper.eq(ComplaintInfo::getId, baseInfoVoId);
        }

        complaintInfoWrapper.set(ComplaintInfo::getIsAcceptance, complaintBaseInfoVo.getIsAcceptance());
        complaintInfoWrapper.set(ComplaintInfo::getAcceptanceDate, complaintBaseInfoVo.getAcceptanceDate());
        complaintInfoWrapper.set(ComplaintInfo::getIsRegister, registerAcceptance.getIsRegister());
        complaintInfoWrapper.set(ComplaintInfo::getFilingHandlingDate, registerAcceptance.getRegisterDate());
        complaintInfoWrapper.set(ComplaintInfo::getComplaintDate, complaintBaseInfoVo.getComplaintDate());
        complaintInfoWrapper.set(ComplaintInfo::getMediateDate, complaintBaseInfoVo.getMediateDate());
        complaintInfoMapper.update(complaintInfoWrapper);
    }
}
